<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App;
use Cache, Artisan;

class InPressArticle extends Model
{
    public $issue;
	const UPLOAD_DIR = 'uploads';
    protected $table='in_press_articles';
    protected $fillable = ['journal_id', 'title', 'title_cn', 'doi_number', 'abstract', 'abstract_cn', 'authors', 'affiliation', 'keywords', 'fund_info', 'images', 'pdf', 'download_count', 'view_count', 'is_online', 'publish_date'];

    public function getTitle()
    {
        if (App::getLocale() == 'cn' && $this->title_cn) {
            return $this->title_cn;
        }
        return $this->title;
    }

    public function getAbstract()
    {
    	if (App::getLocale() == 'cn' && $this->abstract_cn) {
            return $this->abstract_cn;
        }
        return $this->abstract;
    }

    public function authorWithoutAff()
    {
        if (preg_match('/.*<p>(.*?)<\/p>$/i', $this->authors, $matches)) {
            $this->authors = $matches[1];
        }
        return trim(preg_replace('/(<.*?>.*?<\/.*?>|,\*)/', '', $this->authors), ',');
    }

    public function getPureAuthor()
    {
        $author = preg_replace('/(<sup.*?sup>|,\S{1})|\*/', '', $this->authors);

        return $author;
    }


    public function journal()
    {
        return $this->belongsTo(Journal::class);
    }

    public function getKeywordsArr()
    {
        return preg_split('/;\s*/', $this->keywords);
    }

    
    public function getFilePath()
    {
        return public_path('uploads/' . $this->pdf);
    }

    public function fileSize($type = 'pdf')
    {
        $size = '0kb';
        switch ($type) {
            case 'pdf':
            if ($this->pdf) {
                if (file_exists($this->getFilePath())) {
                    $size =  round(filesize($this->getFilePath()) / 1024) . 'kb';
                }
            }
                break;

            default:
                return '0kb';
                break;

            return '0kb';
        }

        return $size;
    }

    public function getRelatedArticles()
    {
        return Article::orderBy('created_at', 'desc')->limit(6)->get();
    }

    public function getUrl()
    {
        return route('press_article.index', ['id' => $this->id]);
    }
}
